package com.tencent.hummingbird.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tencent.hummingbird.portal.exception.ServiceException;
import com.tencent.hummingbird.portal.mapper.QuestionMapper;
import com.tencent.hummingbird.portal.mapper.UserMapper;
import com.tencent.hummingbird.portal.pojo.Answer;
import com.tencent.hummingbird.portal.mapper.AnswerMapper;
import com.tencent.hummingbird.portal.pojo.Question;
import com.tencent.hummingbird.portal.pojo.User;
import com.tencent.hummingbird.portal.service.IAnswerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencent.hummingbird.portal.vo.AnswerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yxb
 * @since 2024-01-10
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements IAnswerService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AnswerMapper answerMapper;
    @Override
    public Answer saveAnswer(String username, AnswerVO answerVO) {
        User user = userMapper.findUserByUsername(username);
        Answer answer = new Answer();
        answer.setContent(answerVO.getContent())
                .setUserId(user.getId())
                .setQuestId(answerVO.getQuestionId())
                .setUserNickName(user.getNickname())
                .setLikeCount(0)
                .setCreatetime(LocalDateTime.now())
                .setAcceptStatus(0);
        int result = answerMapper.insert(answer);
        if (result!=1){
            throw ServiceException.busy();
        }
        return answer;
    }
    @Autowired
    private QuestionMapper questionMapper;
    @Override
    public List<Answer> getAnswersByQuestionId(Integer questionId) {
        /*QueryWrapper<Answer> query = new QueryWrapper();
        query.eq("quest_id", questionId);
        query.orderByDesc("createtime");
        List<Answer> answers = answerMapper.selectList(query);*/
        List<Answer> answers = answerMapper.findAnswersWithCommentByQuestionId(questionId);
        return answers;
    }

    @Override
    @Transactional
    public void accept(Integer answerId, Integer questionId) {
        int num1 = answerMapper.updateAcceptStatus(answerId,1);
        if(num1!=1){
            throw ServiceException.busy();
        }
        int num2 = questionMapper.updateStatus(questionId,2);
        if(num2!=1) {
            throw ServiceException.busy();
        }
    }
}
